<template>
  <div class="rich-text-editor">
    <!-- QuillEditor 组件 -->
    <QuillEditor
      ref="quillEditorRef"
      v-model:content="content"
      contentType="html"
      :options="editorOptions"
      @ready="onEditorReady"
      style="height: 400px; margin-bottom: 20px;"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { QuillEditor, Quill } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import ChartBlot from './ChartBlot';

const Delta = Quill.import('delta');

// Register custom formats before creating editor
Quill.register('formats/chart', ChartBlot, true);

// 编辑器内容（使用 HTML 格式）
const content = ref('<p>点击编辑区域开始输入内容，或双击/拖动左侧图表将其插入到编辑器中</p>');

// 获取编辑器实例和文件 input 的引用
const quillEditorRef = ref(null);

// 编辑器实例准备就绪后的回调
const quillInstance = ref(null);
const onEditorReady = (quill) => {
  quillInstance.value = quill;
  
  // Add chart format to whitelist
  quill.clipboard.addMatcher('DIV', (node, delta) => {
    if (node.classList.contains('embedded-chart-blot')) {
      const chartOptions = JSON.parse(node.getAttribute('data-options'));
      return delta.compose(new Delta().insert({ chart: chartOptions }));
    }
    return delta;
  });
  
  console.log('Quill 实例已准备就绪:', quill);
};

// Expose quillInstance for parent component
defineExpose({ quillInstance });

// 编辑器配置选项
const editorOptions = reactive({
  theme: 'snow',
  modules: {
    clipboard: {
      matchVisual: false,
    },
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'indent': '-1'}, { 'indent': '+1' }],
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],
      ['link'],
      ['clean']
    ]
  },
  placeholder: '请输入内容...',
});

// 组件卸载时清理
onUnmounted(() => {
  quillInstance.value = null;
});
</script>

<style scoped>
.rich-text-editor {
  width: 100%;
}

:deep(.ql-container) {
  font-family: 'Helvetica', 'Arial', sans-serif;
  font-size: 16px;
  color: red;
}

:deep(.ql-editor) {
  /* color: #000; */
}

:deep(.ql-toolbar) {
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

:deep(.ql-container) {
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
}

:deep(.embedded-chart-blot) {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}

:deep(.chart-container) {
  width: 100%;
  min-height: 300px;
}
</style>
